package com.liuhouse.service.impl;

import com.google.gson.Gson;
import com.liuhouse.enums.AppHttpCodeEnum;
import com.liuhouse.exception.SystemException;
import com.liuhouse.service.OssUploadService;
import com.liuhouse.utils.PathUtils;
import com.liuhouse.utils.ResponseResult;
import com.qiniu.common.QiniuException;
import com.qiniu.http.Response;
import com.qiniu.storage.Configuration;
import com.qiniu.storage.Region;
import com.qiniu.storage.UploadManager;
import com.qiniu.storage.model.DefaultPutRet;
import com.qiniu.util.Auth;
import lombok.Data;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.io.FileInputStream;
import java.io.InputStream;

@ConfigurationProperties(prefix = "myoss")
@Data
@Service
public class OssUploadServiceImpl implements OssUploadService {

    private String accessKey;
    private String secretKey;
    private String bucket;

    //进行文件上传的解接口实现  MultipartFile 是spring提供的上传接口
    @Override
    public ResponseResult uploadImg(MultipartFile img) {
        //获取原始文件名称
        String originalFilename = img.getOriginalFilename();
        //读取文件大小
        long fileSize = img.getSize();
        //判断文件大小是否超过2MB(2MB=2*1024*1024)
        if(fileSize > 2*1024*1024){
            //抛出文件大小超过限制的异常
            throw new SystemException(AppHttpCodeEnum.FILE_SIZE_ERROR);
        }

        //对原始的文件名称进行判断,只能上传 .jpg 或者  .png文件
        if(!originalFilename.endsWith(".png") && !originalFilename.endsWith(".jpg")){
            //AppHttpCodeEnum我们自己定义的枚举类
            throw new SystemException(AppHttpCodeEnum.FILE_TYPE_ERROR);
        }
        //如果满足判断条件,则上传文件到七牛云的OSS，并得到一个图片外链访问地址,PathUtils使我们自己定义的工具类
        String filePath = PathUtils.generateFilePath(originalFilename);
        //上传文件 ， 返回文件的地址字符串
        String url = uploadOss(img, filePath);
        //把得到的外链地址返回给前端
        return ResponseResult.okResult(url);
    }

    //上传文件的具体代码,
    public String uploadOss(MultipartFile imgFile , String filePath){
        //构造一个带指定 Region 对象的配置类
        Configuration cfg = new Configuration(Region.autoRegion());
        cfg.resumableUploadAPIVersion = Configuration.ResumableUploadAPIVersion.V2;// 指定分片上传版本
//...其他参数参考类注释
        UploadManager uploadManager = new UploadManager(cfg);
////...生成上传凭证，然后准备上传
//        String accessKey = "your access key";
//        String secretKey = "your secret key";
//        String bucket = "your bucket name";
//默认不指定key的情况下，以文件内容的hash值作为文件名
        String key = filePath;
        try {
//            byte[] uploadBytes = "hello qiniu cloud".getBytes("utf-8");
//            ByteArrayInputStream byteInputStream=new ByteArrayInputStream(uploadBytes);
            //上面两行是官方写的(注释掉),下面那几行是我们写的

//            InputStream inputStream = new FileInputStream("C:\\Users\\Administrator\\Desktop\\6.jpg");
            //将前端传过来的文件转换成inputStream对象
            InputStream inputStream = imgFile.getInputStream();

            Auth auth = Auth.create(accessKey, secretKey);
            String upToken = auth.uploadToken(bucket);
            try {
                Response response = uploadManager.put(inputStream,key,upToken,null, null);
                //解析上传成功的结果
                DefaultPutRet putRet = new Gson().fromJson(response.bodyString(), DefaultPutRet.class);
                System.out.println("上传成功!生成的key是 :" + putRet.key);
                System.out.println("上传成功,生成的hash是: " + putRet.hash);
                return "http://blog.xiaobangcai.com/"+key;
            } catch (QiniuException ex) {
                ex.printStackTrace();
                if (ex.response != null) {
                    System.err.println(ex.response);
                    try {
                        String body = ex.response.toString();
                        System.err.println(body);
                    } catch (Exception ignored) {
                    }
                }
            }
        } catch (Exception ex) {
            //ignore
        }
        return "上传失败";
    }

}
